package com.example.design.函数式编程.a函数对象化;

import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 函数对象化->行为参数化
 */
public class Sample01 {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student student1 = new Student("张无忌", "男", 18);
        Student student2 = new Student("q", "女", 16);
        Student student3 = new Student("b", "男", 19);
        Student student4 = new Student("c", "女", 20);
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);

        // 参数 -> 逻辑部分
        // student->student.equals("男")
        // 在这个例子中也可以使用jdk的函数式接口Predicate
        List<Student> man = filter(students, student -> student.sex.equals("男"));
        List<Student> age = filter(students, student -> student.age < 18);
        System.out.println(JSON.toJSONString(man));
        System.out.println(JSON.toJSONString(age));
    }


    interface Lamdba {
        Boolean filter(Student student);
    }

    // 参数 -> 逻辑部分
    static List<Student> filter(List<Student> students, Lamdba lamdba) {
        List<Student> studentList = new ArrayList<>();
        for (Student student : students) {
            if (lamdba.filter(student)) {
                studentList.add(student);
            }
        }

        return studentList;
    }

    @Data
    static public class Student {
        String name;
        String sex;
        int age;

        public Student() {
        }

        public Student(String name) {
            this.name = name;
        }

        public Student(String name, String sex, int age) {
            this.name = name;
            this.sex = sex;
            this.age = age;
        }

        /**
         * 方法引用对应的函数对象：(stu) -> stu.isMale()
         * @return
         */
        public boolean isMale() {
            return this.sex.equals("男");
        }

        /**
         * 对应的函数对象 (stu) -> stu.print
         */
        public void print(){
            System.out.println(this);
        }
    }
}
